package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"rk11_6-tech/caches"
	"rk11_6-tech/models"
	"strconv"
	"time"
)

func Lists(c *gin.Context) {
	var list []models.Good
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "2"))
	offset := (page - 1) * pageSize
	redis_key := "Good_list" + strconv.Itoa(page)
	cacheData, _ := caches.Rdb.Get(caches.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(pageSize).Find(&list)
		jsonData, _ := json.Marshal(&list)
		caches.Rdb.Set(caches.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	models.DB.Offset(offset).Limit(pageSize).Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": list,
	})
	return
}
